<?php

/**
 * 
 * ClientEngage: ClientEngage Visitor Voice (http://www.clientengage.com)
 * Copyright 2012, ClientEngage (http://www.clientengage.com)
 *
 * You must have purchased a valid license from CodeCanyon in order to have 
 * the permission to use this file.
 * 
 * You may only use this file according to the respective licensing terms 
 * you agreed to when purchasing this item on CodeCanyon.
 * 
 * 
 * 
 *
 * @author          ClientEngage <contact@clientengage.com>
 * @copyright       Copyright 2013, ClientEngage (http://www.clientengage.com)
 * @link            http://www.clientengage.com ClientEngage
 * @since           ClientEngage - Visitor Voice v 1.0
 * 
 */
App::uses('AppController', 'Controller');

/**
 * Users Controller
 *
 * @property User $User
 */
class UsersController extends AppController
{

    public $name = 'Users';

    /**
     * index method
     *
     * @return void
     */
    public function admin_index()
    {
        $this->set('title_for_layout', __('Users'));

        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function admin_view($id = null)
    {
        $this->set('title_for_layout', __('View User'));

        $this->User->id = $id;
        if (!$this->User->exists())
        {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('user', $this->User->find('first', array('conditions' => array('User.id' => $id))));
    }

    /**
     * add method
     *
     * @return void
     */
    public function admin_add()
    {
        $this->set('title_for_layout', __('Add User'));

        if ($this->request->is('post'))
        {
            $this->User->create();
            if ($this->User->save($this->request->data))
            {
                $this->Session->setFlash(__('The user has been saved'), Flash::Success);
                $this->redirect(array('action' => 'view', $this->User->id));
            }
            else
            {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'), Flash::Warning);
            }
        }
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function admin_edit($id = null)
    {
        $this->set('title_for_layout', __('Edit User'));

        $this->User->id = $id;
        if (!$this->User->exists())
        {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put'))
        {
            if ($this->User->saveAll($this->request->data))
            {
                $this->Session->setFlash(__('The user has been saved'), Flash::Success);
                $this->redirect(array('action' => 'view', $this->User->id));
            }
            else
            {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'), Flash::Warning);
            }
        }
        else
        {
            $this->request->data = $this->User->find('first', array('conditions' => array('User.id' => $id)));
        }
    }

    /**
     * delete method
     *
     * @throws MethodNotAllowedException
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function admin_delete($id = null)
    {
        if (!$this->request->is('post'))
        {
            throw new MethodNotAllowedException();
        }
        $this->User->id = $id;
        if (!$this->User->exists())
        {
            throw new NotFoundException(__('Invalid user'));
        }

        if ($this->User->find('count') < 2)
        {
            $this->Session->setFlash(__('You cannot delete the only administrator'));
            $this->redirect($this->referer());
        }

        if ($this->User->delete())
        {
            $this->Session->setFlash(__('User deleted'), Flash::Success);
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('User was not deleted'), Flash::Error);
        $this->redirect(array('action' => 'index'));
    }

    public function login()
    {
        $this->set('title_for_layout', __('Login'));

        $this->__login();
        $this->render('login');
    }

    public function beforeFilter()
    {
        parent::beforeFilter();
        $this->Auth->allow('login', 'logout');
    }

    private function __login()
    {
        $this->layout = 'default';

        if (AuthComponent::user())
            $this->redirect(array('controller' => 'visitorforms', 'action' => 'index', 'admin' => true));

        if ($this->request->is('post'))
        {
            $this->User->set($this->request->data);
            if ($this->Auth->login())
            {
                $this->Session->setFlash(__('You successfully logged in.'), Flash::Success);
                if (!empty($this->request->params['admin']))
                    $this->redirect(array('controller' => 'visitorforms', 'action' => 'index', 'admin' => true));
                else
                    $this->redirect($this->Auth->redirectUrl());
            } else
            {
                unset($this->request->data['User']['password']);
                $this->Session->setFlash(__('The username/password you provided were incorrect.'));
            }
        }
        $this->set('title_for_layout', __('Login'));
    }

    public function logout()
    {
        $this->redirect($this->Auth->logout());
    }

    public function admin_profile()
    {
        $this->set('title_for_layout', __('Your Profile'));

        $this->User->id = AppAuth::user('id');
        if (!$this->User->exists())
        {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put'))
        {
            $this->request->data['User']['id'] = $this->User->id;
            if ($this->User->save($this->request->data))
            {
                $this->Session->setFlash(__('The changes to your profile were saved'), Flash::Success);
                $this->Session->write('Auth', $this->User->read(null, AppAuth::user('id')));
                $this->redirect(array('action' => 'profile'));
            }
            else
            {
                $this->Session->setFlash(__('Your profile could not be saved. Please, try again.'), Flash::Warning);
            }
        }
        else
        {
            $this->request->data = $this->User->find('first', array('conditions' => array('User.id' => AppAuth::user('id'))));
        }
        $this->set('title_for_layout', __('Your Profile'));
        $user = $this->User->find('first', array('conditions' => array('User.id' => AppAuth::user('id'))));
        $this->set(compact('user'));
    }

}
